﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quartz;
using ZHDJ.Core.Log;
using ZHDJ.Data;
using ZHDJ.Data.Models.Common;
using ZHDJ.WinService.Util;

namespace ZHDJ.WinService.Job
{
    /// <summary>
    /// 定时作业（sql）管理服务
    /// </summary>
    public class RunScheduledJob : JobBase
    {
        /// <summary>
        /// 执行业务锁
        /// </summary>
        private static Object BusinessLock = new Object();


        public override JobSetInfo JobSetInfo
        {
            get
            {
                return new JobSetInfo()
                {
                    JobGroup = "ScheduledJobGroup",
                    JobName = "ScheduledJobJob",
                    //
                    TriggerName = "ScheduledJobTrigger",
                    Cron = ConfigHelper.ScheduledJobIntervalCron
                };
            }
        }


        public override void RunBusiness(IJobExecutionContext context)
        {
            lock (BusinessLock)
            {
                using (var DB = (new DBInstance()).DB)
                {
                    var scheduledJob = DB.ScheduledJobs.Where(a => !string.IsNullOrEmpty(a.JobCron) &&
                                                                  !string.IsNullOrEmpty(a.JobFlag) &&
                                                                   !string.IsNullOrEmpty(a.JobName) &&
                                                                   !string.IsNullOrEmpty(a.JobSql) && a.JobFlag!= "Test");
                    if (scheduledJob.ToList().Count == 0)
                    {
                        ScheduleHelper.RunProcedureJobList.ForEach(DeleteJob);
                        return;
                    }
                    //配置作业
                    if (ScheduleHelper.RunProcedureJobList.Count == 0)
                    {
                        scheduledJob.ToList().ForEach(a => LogHelper.Info("增加定时作业====" + a.JobCron + "==" + a.JobFlag + "==" + a.JobName + "==" + a.JobSql, "ScheduledJob"));
                        //创建
                        scheduledJob.ToList().ForEach(AddJob);
                    }
                    else
                    {
                        //删除没有的作业
                        var deletejob =
                            ScheduleHelper.RunProcedureJobList.Where(a => !scheduledJob.Select(b => b.JobFlag).Contains(a.JobFlag))
                                .ToList();
                        if (deletejob.Count > 0)
                        {
                            deletejob.ForEach(a => LogHelper.Info("删除定时作业====" + a.JobCron + "==" + a.JobFlag + "==" + a.JobName + "==" + a.JobSql, "ScheduledJob"));
                            deletejob.ForEach(DeleteJob);
                            
                        }
                        //增加 新增的作业
                        var runJob = ScheduleHelper.GetScheduledJobIDList();
                        foreach (var job in scheduledJob)
                        {
                            if (!runJob.Contains(job.JobFlag))
                            {
                                LogHelper.Info("增加定时作业====" + job.JobCron + "==" + job.JobFlag + "==" +
                                                       job.JobName + "==" + job.JobSql, "ScheduledJob");
                                AddJob(job);
                            }
                        }
                        //var newjob =
                        //    scheduledJob.Where(a => !runJob.Contains(a.JobFlag))
                        //        .ToList();
                        //if (newjob.Count > 0)
                        //{
                        //    newjob.ToList()
                        //        .ForEach(
                        //            a =>
                        //                LogHelper.Info("增加定时作业====" + a.JobCron + "==" + a.JobFlag + "==" +
                        //                               a.JobName + "==" + a.JobSql));
                        //    newjob.ForEach(AddJob);
                        //}
                    }
                    //验证作业是否已更新
                    var updateJob = scheduledJob.Where(a => a.IsUpdate).ToList();
                    if (updateJob.Count > 0)
                    {
                        foreach (var item in scheduledJob.Where(a => a.IsUpdate))
                        {
                            item.IsUpdate = false;
                        }
                        DB.SaveChanges();
                        updateJob.ToList().ForEach(a => LogHelper.Info("更新定时作业====" + a.JobCron + "==" + a.JobFlag + "==" + a.JobName + "==" + a.JobSql, "ScheduledJob"));
                        updateJob.ForEach(a => ScheduleHelper.DeleteJob(a.JobFlag + "Job", a.JobFlag + "Group"));
                        updateJob.ForEach(AddJob);

                    }
                }
            }

        }

        private void AddJob(ScheduledJob jobSet)
        {
            try
            {
                var runProcedureJob = new RunProcedureJob(jobSet.JobFlag, jobSet.JobName, jobSet.JobSql, jobSet.JobCron);
                var scheduledJobInfo = new ScheduledJobInfo(jobSet.JobFlag, jobSet.JobName, jobSet.JobCron,jobSet.JobSql
                    );
                ScheduleHelper.AddJob(runProcedureJob);
                ScheduleHelper.RunProcedureJobList.Add(scheduledJobInfo);
            }
            catch (Exception ex)
            {
                LogHelper.Error("增加定时作业失败：" + jobSet.JobName);
                LogHelper.Error(ex);
            }
        }

        private void DeleteJob(ScheduledJobInfo runProcedureJob)
        {
            try
            {
                ScheduleHelper.DeleteJob(runProcedureJob.JobFlag + "Job", runProcedureJob.JobFlag + "Group");
                ScheduleHelper.RemoveRunProcedureJobList(runProcedureJob);
            }
            catch (Exception ex)
            {
                LogHelper.Error("删除定时作业失败：" + runProcedureJob.JobName);
                LogHelper.Error(ex);
            }
        }

        public override void OnStart()
        {


        }
    }


}
